import 'package:flutter/material.dart';
import 'package:flutter_wechat/constants.dart';
import 'package:flutter_wechat/page/address_list_page.dart';
import 'package:flutter_wechat/page/chat_list_page.dart';
import 'package:flutter_wechat/page/discovery_page.dart';
import 'package:flutter_wechat/page/myself_page.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
//    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.light.copyWith(
//      statusBarColor: Colors.white,
//    ));
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        cardColor: Colors.white,
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _currentIndex = 0;
  PageController _pageController = PageController(initialPage: 0);
  List<ChatItemModel> _list = mockData();
  int _count = 0;

  @override
  void initState() {
    super.initState();
    var count = _list.fold<int>(0, (i1, i2) => i1 + i2.unreadCount);
    setState(() {
      _count = count;
    });
  }

  bool _showFlag = false;

  _onSelected(String value) {
    print('value: $value');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        color: Colors.white,
        alignment: Alignment.center,
        child: PageView(
          controller: _pageController,
          onPageChanged: _onTap,
          children: <Widget>[
            ChatListPage(list: _list, onSelected: _onSelected),
            AddressListPage(onSelected: _onSelected),
            DiscoveryPage(onSelected: _onSelected),
            MySelfPage(),
          ],
        ),
      ),
      bottomNavigationBar: BottomNavigationBar(
        iconSize: 26.0,
        items: [
          BottomNavigationBarItem(
              activeIcon: _UnreadIcon(icon: Icon(messageIcon), count: _count),
              icon: _UnreadIcon(icon: Icon(messageEmptyIcon), count: _count),
              title: Text("微信")),
          BottomNavigationBarItem(
              activeIcon: Icon(addressList2Icon),
              icon: Icon(addressListIcon),
              title: Text("通讯录")),
          BottomNavigationBarItem(
              activeIcon: Icon(faxian2Icon),
              icon: Icon(faxianIcon),
              title: Text("发现")),
          BottomNavigationBarItem(
              activeIcon: Icon(myself2Icon),
              icon: Icon(myselfIcon),
              title: Text("我"))
        ],
        type: BottomNavigationBarType.fixed,
        currentIndex: _currentIndex,
        onTap: _onTap,
        fixedColor: Color(0xff08C161),
      ),
    );
  }

  void _onTap0() {
    if (_showFlag) {
      setState(() {
        _showFlag = false;
      });
    }
  }

  void _onTap(int index) {
    setState(() {
      _currentIndex = index;
      _pageController.animateToPage(index,
          duration: Duration(milliseconds: 10), curve: Curves.bounceIn);
    });
    _onTap0();
  }

  void _menuOnTap(ShowMenuModel value) {
    print("menu ontap: $value");
  }
}

AppBar getMyAppBar({PopupMenuItemSelected<String> onSelected, String title}) {
  return AppBar(
    backgroundColor: Color(0xffEDEDED),
    elevation: 0.0,
    title: Text(title, style: TextStyle(color: Colors.black, fontSize: 18.0)),
    actions: <Widget>[
      IconButton(
          icon: Icon(Icons.search, color: Colors.black), onPressed: null),
      Theme(
          data: ThemeData(cardColor: Color(0xff494949)),
          child: PopupMenuButton<String>(
            child: IconButton(
                icon: Icon(Icons.add_circle_outline, color: Colors.black),
                onPressed: null),
            //这是点击弹出菜单的操作，点击对应菜单后，改变屏幕中间文本状态，将点击的菜单值赋予屏幕中间文本
            onSelected: onSelected,
            //这是弹出菜单的建立，包含了两个子项，分别是增加和删除以及他们对应的值
            itemBuilder: (BuildContext context) => <PopupMenuEntry<String>>[
                  PopupMenuItem(
                    child: MyPopupMenu(
                        title: "发起群聊",
                        icon: Icon(messageIcon, color: Colors.white)),
                    value: '发起群聊',
                  ),
                  PopupMenuItem(
                    child: MyPopupMenu(
                        title: "添加朋友",
                        icon: Icon(Icons.person_add, color: Colors.white)),
                    value: '添加朋友',
                  ),
                  PopupMenuItem(
                    child: MyPopupMenu(
                        title: "扫一扫",
                        icon: Icon(sweepIcon, color: Colors.white)),
                    value: '扫一扫',
                  ),
                  PopupMenuItem(
                    child: MyPopupMenu(
                        title: "收付款", icon: Icon(sfkIcon, color: Colors.white)),
                    value: '收付款',
                  ),
                  PopupMenuItem(
                    child: MyPopupMenu(
                        title: "帮助与反馈",
                        icon: Icon(Icons.mail, color: Colors.white)),
                    value: '帮助与反馈',
                  ),
                ],
          )),
    ],
  );
}

class ShowMenuModel {
  final String title;
  final Icon icon;

  const ShowMenuModel({this.title, this.icon});

  @override
  String toString() {
    return 'ShowMenuModel{title: $title, icon: $icon}';
  }
}

class _ShowMenuList extends StatelessWidget {
  final ValueChanged<ShowMenuModel> onTap;
  final List<ShowMenuModel> list;

  const _ShowMenuList({Key key, this.onTap, this.list}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final query = MediaQuery.of(context);
    final width = (query.size.width - 20.0) / 2.0;
    final separatorWidth = width - 24 - 20 - 10;
    return Container(
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(5.0), color: Color(0xff4c4c4c)),
      alignment: Alignment.center,
      height: 280.0,
      width: width,
      padding: EdgeInsets.all(5.0),
      child: ListView.separated(
          itemBuilder: (context, index) => _ShowMenuItemWidget(
              model: list[index],
              len: list.length,
              onTap: () => onTap(list[index])),
          separatorBuilder: (context, index) =>
              _ShowMenuSeparatorWidget(width: separatorWidth),
          itemCount: list.length),
    );
  }
}

class _ShowMenuSeparatorWidget extends StatelessWidget {
  final double width;

  const _ShowMenuSeparatorWidget({Key key, this.width});

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.end,
      children: <Widget>[
        Container(
          height: 0.2,
          width: width,
          color: Colors.grey,
        ),
      ],
    );
  }
}

class _ShowMenuItemWidget extends StatelessWidget {
  final ShowMenuModel model;
  final int len;
  final VoidCallback onTap;

  const _ShowMenuItemWidget({Key key, this.model, this.len, this.onTap})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: onTap,
      child: Container(
        alignment: Alignment.center,
        height: (280 - 15) / len,
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Padding(
              child: model.icon,
              padding: EdgeInsets.symmetric(horizontal: 10.0),
            ),
            Text(model.title,
                style: TextStyle(fontSize: 18.0, color: Colors.white)),
          ],
        ),
      ),
    );
  }
}

class _UnreadIcon extends StatelessWidget {
  final Widget icon;
  final int count;

  const _UnreadIcon({this.icon, this.count});

  @override
  Widget build(BuildContext context) {
    return Stack(
      alignment: Alignment.topRight,
      children: <Widget>[
        Container(
          child: icon,
          margin: EdgeInsets.all(3.0),
        ),
        Offstage(
            child: CircleAvatar(
                child: Text(count.toString(),
                    style: TextStyle(
                        fontSize: 12.0,
                        color: Colors.white,
                        fontWeight: FontWeight.bold)),
                backgroundColor: Colors.red,
                radius: 9.0),
            offstage: count == 0)
      ],
    );
  }
}
